package com.yj.service.impl;

import com.yj.entity.Users;
import com.yj.dao.UsersMapper;
import com.yj.service.IUsersService;
import com.yj.util.PageUtil;
import com.yj.util.UpLoad;
import com.yj.vo.JsonResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yj
 * @since 2020-08-24
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

	@Autowired
	UsersMapper users;
	
	@Override
	public JsonResult zuCe(Users user) {
		int n = 0;
		JsonResult ret = null;
		//加密密码
		user.setPassword(users.MdPassword(user.getPassword()));
		n = users.insert(user);
		if(n!=0) {
			ret = new JsonResult(true, "注册成功");
			ret.setData("username", user.getUname());
			return ret;
		}else {
			ret = new JsonResult(false, "注册失败");
			return ret;
		}
	}

	@Override
	public JsonResult login(String uemail, String pass,HttpSession session) {
		JsonResult ret = null;
		QueryWrapper<Users> wrapper = new QueryWrapper<Users>();
		wrapper.eq("uemail", uemail);
		wrapper.eq("password", users.MdPassword(pass));
		List<Users> list = users.selectList(wrapper);
		
		if(list.size()!=0) {
			
			ret = new JsonResult(true, "登陆成功");
			session.setAttribute("usersession", list.get(0));
			ret.setData("user", list.get(0));
			
			return ret;
		}else {
			
			ret = new JsonResult(false, "邮箱或密码错误");
			return ret;
		}
	}

	@Override
	public JsonResult updataUser(Users user) {
		JsonResult ret = null;
		String password = user.getPassword();
		String mdPassword = users.MdPassword(password);
		user.setPassword(mdPassword);
		int n = users.updateById(user);
		if(n!=0) {
			Users use=users.selectById(user.getUid());
			ret = new JsonResult(true, "用户信息更新成功");
			ret.setData("user", use);
			return ret;
		}else {
			
		}
		
		return ret;
	}

	@Override
	public JsonResult upLoadImg(int uid, MultipartFile files) {
		JsonResult ret = null;
		String imgName = UpLoad.upload(files);
		int n = users.UpdateImgById(uid, imgName);
		if(n!=0) {
			ret = new JsonResult(true, "头像上传成功");
			ret.setData("info", "ok");
			return ret;
		}else {
			ret = new JsonResult(false, "头像上传失败");
			return ret;
		}
	}

	@Override
	public JsonResult pages() {
		
		return PageUtil.pages(users, null, 6);
	}

	@Override
	public JsonResult page(int pageNum) {
		
		return PageUtil.page(pageNum, 6, users, null);
	}

	@Override
	public JsonResult delUser(int uid) {
		JsonResult jsonResult=new JsonResult(false, null);
		int num=users.deleteById(uid);
		if (num>0) {
			jsonResult.setMessage("删除成功");
		}else {
			jsonResult.setMessage("删除失败");
		}
		return jsonResult;
	}

}
